﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SmallJob.Model;
using SmallJob.Services.Interfaces;
using SmallShop.Services.Implements;
using SmallShop.Services.Interfaces;

namespace BackEnd.Controllers
{
    [Authorize]
    public class RequestController : Controller
    {
        //
        // GET: /Request/
        private readonly IRequestService _RequestService;
        private readonly IUserService _UserService;
        private readonly ICategoryService _CategoryService;
        private readonly IBidRequestService _BidRequestService;

        public RequestController(IRequestService RequestService, IUserService UserService, ICategoryService CategoryService, IBidRequestService BidRequestService)
        {
            _RequestService = RequestService;
            _UserService = UserService;
            _CategoryService = CategoryService;
            _BidRequestService = BidRequestService;
        }
        public ActionResult Index(string page, string filter)
        {
            if (string.IsNullOrWhiteSpace(page))
            {
                page = "1";
            }
            ViewData["tableindex"] = new { page = page, pagesize = Convert.ToInt32(Resources.Resource.ItemPerPage), filter = filter };
            return View();
        }
        public ActionResult TableRequest(int page, int pagesize, string filter)
        {
            int total = 0;
            pagesize = Convert.ToInt32(Resources.Resource.ItemPerPage);
            if (page == 0)
            {
                page = 1;
            }
            var model = _RequestService.GetAllByPage(page, pagesize, out total);
            if (!string.IsNullOrWhiteSpace(filter))
            {
                model = _RequestService.GetAllByPageFilter(page, pagesize, out total, filter);
                ViewData["filter"] = filter;
            }
            model = UtilityService.RequestLoadUser(model, _UserService);
            model = UtilityService.RequestLoadCategory(model, _CategoryService);
            if ((total % pagesize) > 0)
            {
                ViewData["total"] = (total / pagesize) + 1;
            }
            else
            {
                ViewData["total"] = total / pagesize;
            }
            ViewData["curpage"] = page;
            ViewData["nextpage"] = page + 1;
            ViewData["prepage"] = page - 1;
            return PartialView(model);
        }
        public ActionResult Add()
        {
            if (!User.Identity.IsAuthenticated)
                return RedirectToAction("index", "home");
            int id = 0;
            try
            {
                id = Convert.ToInt32(RouteData.Values["id"]);
            }
            catch
            {
                id = 0;
            }
            var request = _RequestService.GetById(id);
            if (request == null)
            {
                request = new Request()
                {
                    ID = 0,
                    Price = 0,
                    Description = "",
                    EndDate = DateTime.Now,
                    CategoryID = 0,
                    Title = "",
                    Location = "",
                    AssignedUserID = 0
                };
            }
            List<Category> listCate = null;
            listCate = _CategoryService.GetAllAvaiable();
            ViewData["AllCate"] = listCate;
            return View(request);
        }
        [ValidateInput(false)]
        public ActionResult Save(int id, string description, string title, string location, int cateID, string endDate, string forwardemail, string forwardphone)
        {
            if (!User.Identity.IsAuthenticated)
                return RedirectToAction("index", "Home");
            var request = _RequestService.GetById(id);
            if (request == null)
                request = new Request()
                {
                    ID = 0,
                    Price = 0,
                    Description = "",
                    EndDate = DateTime.Now,
                    CategoryID = 0,
                    Title = "",
                    Location = "",
                    AssignedUserID = 0,
                    StartDate = DateTime.Now,
                    CreatedDate = DateTime.Now
                };
            request.Title = title;
            request.Location = location;
            request.CategoryID = cateID;
            request.ForwardEmail = forwardemail;
            request.ForwardPhone = forwardphone;
            request.Description = HttpUtility.HtmlEncode(description);
            request.ModifiedDate = DateTime.Now;
            request.EndDate = DateTime.ParseExact(endDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
            try
            {
                request.Price = Convert.ToInt32(Request.Form["price"]) * 1000;
            }
            catch
            {
                ModelState.AddModelError("PriceInvalid", "Nhập Đúng Giá");
            }
            if (string.IsNullOrWhiteSpace(request.Title))
                ModelState.AddModelError("TitleInvalid", "Tiêu đề không được bỏ trông");
            if (string.IsNullOrWhiteSpace(request.Location))
                ModelState.AddModelError("LocationInvalid", "Địa điểm không được bỏ trông");
            if (string.IsNullOrWhiteSpace(request.Description))
                ModelState.AddModelError("DescriptionOrderInvalid", "Nội dung không được bỏ trông");

            if (ModelState.IsValid)
            {
                if (request.ID == 0)
                {
                    _RequestService.Add(request);
                    TempData["mess"] = "Thêm thành công!";
                    TempData["rID"] = request.ID;
                    request.AssignedUser = _UserService.GetById(request.AssignedUserID);
                    return RedirectToAction("Add");
                }
                else
                {
                    _RequestService.Update(request);
                    TempData["mess"] = "Sửa thành công!";
                    TempData["rID"] = request.ID;
                    request.AssignedUser = _UserService.GetById(request.AssignedUserID);
                    return new RedirectResult("/request/add/" + request.ID);
                }
            }
            List<Category> listCate = null;
            listCate = _CategoryService.GetAllAvaiable();
            ViewData["AllCate"] = listCate;
            return View("Add", request);
        }
        public ActionResult Bid(int id)
        {
            var req = _RequestService.GetById(id);
            var listBid = _BidRequestService.GetByRequest(id);
            foreach (var item in listBid)
            {
                item.Bidder = _UserService.GetById(item.BidderID);
            }
            ViewData["request"] = req;
            return PartialView(listBid);
        }
    }
}
